$(function () {
    var query = {},
        $view = $('.btn-view'),
        $delete = $('.btn-delete'),
        $update = $('.btn-update'),
        $create = $('.btn-create'),
        $updatePermission = $('.btn-update-permission'),
        $log = $('.btn-log');
    var config = {
        query: '/role/queryList?',//分页查询URL,
        create: '/role/create',//create,
        update: '/role/update',
        getPermission: '/role/getPermission/',
        // permissions: '/permissions/all',
        'delete': '/role/delete'
    };

    $loading.fadeOut();
    function search(obj,isForce) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        if (!isForce) {
            if (isSameQueryStr(query_, query)) { //查询条件和上次一样，取消请求
                return $loading.fadeOut();
            }
        }
        $.get(config.query + ajaxArgStrGenerator(query), function (res) {
            var _$table = $('.table-responsive .table');
            destroyBtn();
            _$table.$table($.extend(TABLE_SETTING, {
                checkbox: true, // 是否显示复选框
                seqNum: true, // 是否显示序号
                sort: search, //排序回调函数
                destroyBtn: destroyBtn, //禁用按钮
                createBtn: createBtn, // 启用她扭
                toolbar: '.toolbar',
                fixedHeader: false,
                enableSetting: true,//允许自定义显示列
                search: function (obj) { //搜索框查询函数
                    search(obj)
                },
                fields: [
                    {name: 'roleName', label: '角色名称', style: 'width:150px;'},
                    //{name: 'description', label: '描述'},
                ],
                data: res.list || [],
            }));
            var page = res.page;
        });
    }

    function destroyBtn() {
        disableBtn($delete);
        disableBtn($update);
        disableBtn($updatePermission);
        disableBtn($view);
        disableBtn($log);
    }

    function createBtn(this_) {
        var $data = $(this_).data('json');
        enableBtn($view, $data);
        enableBtn($delete, $data);
        enableBtn($update, $data);
        enableBtn($log, $data);
        if ($data.id != 3) {
            enableBtn($updatePermission, $data);
        }
        $('.view-c').html('<div style="margin: 15px;text-align: center;font-size: 12px;"> \
        查看角色权限 \
        </div>')
    }
    onClick($log, function () {
        var $current = $(this).data('json');
        window.location = './../../log/log.html?id=' + $current.id + '&type=role';
    });
    onClick($create, function () {
        var $modal = layerAlert({
            full:true,
            title: '新建角色',
            body: ejs.render($('#form-update').html(), {}),
            shown: function () {
                validate($modal);
            }
        })
    });
    onClick($updatePermission, function () {
        window.location = './detail.html?json=' + encodeURI(JSON.stringify($(this).data('json')));
    });
    onClick($update, function () {
        var $data = $(this).data('json');
        var model = {id: $data.id, name_: $data.roleName};
        var $modal = layerAlert({
            title: '修改角色',
            full:true,
            body: ejs.render($('#form-update').html(), model),
            shown: function () {

                validate($modal);
            }
        })
    });

    onClick($log, function () {
        var $current = $(this).data('json');
        window.location = './../../log/log.html?id=' + $current.id + '&type=role';
    });
    onClick($delete, function () {
        if (confirm("确定删除?")) {
            $.post(config['delete'], {id: $(this).data('json').id}, function (xhr) {
                if (xhr.code == 200) {
                    search({},true);
                    fnSuccess && fnSuccess('删除成功!');
                } else {
                    alert(xhr.error)
                }
            })
        }

    });
    function validate(modal) {
        debugger;
        $('body #create-form')
            .formValidation('destroy').formValidation($.extend({}, VALIDATION_SETTING, {
            fields: {
                name: {
                    row: '.col-xs-7',
                    validators: {
                        notEmpty: {
                            message: '角色名称必填'
                        },
                        stringLength: {
                            min: 2,
                            max: 40,
                            message: '角色名称长度最少2位，最多40位'
                        },
                    }
                },

            }
        }))
            .off('success.form.fv').on('success.form.fv', function (e) {
            e.preventDefault();
            debugger;
            var form = parseSearch($(e.target).serialize());
            var url = '';
            if (form.id) { // is update?
                url = config.update;
            } else {
                url = config.create;
                delete form.id;
            }
            if (form.name) {
                form.name = form.name.trim();
            }
            form.permissions = '';
            $.post(url, form, function (xhr, data) {
                if (xhr.code == 200) {
                    fnSuccess(form.id ? '保存成功' : '创建成功!');

                    search({},true);
                    layer.closeAll();
                    //    modal && modal.modal('hide');
                } else {
                    alert(xhr.error || xhr.msg);
                }
            });
        });
    }


    onClick($view, function () {
        var $data = $(this).data('json');
        $.when(getDataByUrl(config.getPermission + $data.id, '$permission' + $data.id))
            .then(function (list) {
                var menusGroup = _.filter(list, function (item) {
                    return item.type == 1;
                });
                var accessGroup = _.filter(list, function (item) {
                    return item.type == 0;
                });
                $('.view-c').html(renderMenus(menusGroup));
                //+ renderAccess(accessGroup));
            })
            .fail(function (e) {
                console.log(e);
            })
    });



    search({},true);
});